<template>
  <div>
    <el-dialog title="子病管理"
               :visible.sync="visible"
               :before-close="modalClose"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               width="70%">
      <el-button type="primary"
                 @click="handleAdd()">新 增
      </el-button>
      <element-table class="mt-20"
                     :columns="columns"
                     :data="list"
                     pager
                     :pageTotal="pageTotal"
                     :pageIndex="pageIndex"
                     :pageSize="pageSize"
                     @handleChangePage="handleChangePage">
        <template v-slot:option="{row}">
          <el-button type="primary"
                     @click="handleOption('edit', row)">编辑
          </el-button>
          <el-button type="danger"
                     @click="handleOption('del', row)">删除
          </el-button>
        </template>
      </element-table>

    </el-dialog>

    <el-dialog :title="title"
               :visible.sync="showDialog"
               v-loading="loading"
               width="78%">
      <el-form :model="submitData"
               label-position="right"
               label-width="150px"
               ref="formModelRef"
               :rules='formModelRules'>
        <el-form-item label="子病名称：" prop="name">
          <el-input v-model="submitData.name"
                    clearable
                    placeholder="请输入子病名称"
                    style="width: 260px;"/>
        </el-form-item>
        <el-form-item label="子病分类：" prop="type">
          <el-input v-model="submitData.type"
                    clearable
                    type="number"
                    placeholder="请输入子病分类"
                    style="width: 260px;"/>
        </el-form-item>
        <el-form-item label="子病等级：" prop="level">
          <el-input v-model="submitData.level"
                    clearable
                    type="number"
                    placeholder="请输入子病等级"
                    style="width: 260px;"/>
        </el-form-item>

        <el-form-item label="条  件：">
          <span style="font-weight: bold;margin-right: 20px">⊙指标</span>
          <el-button type="primary" @click="handleAdd1()">增 加</el-button>
        </el-form-item>
        <el-form-item v-for="(item,index) in list1" :key="index+'a'">
          <p>条件{{ item.localId }}:</p>
          <el-select v-model="item.genderCondition"
                     clearable
                     style="width: 120px"
                     placeholder="选择性别">
            <el-option v-for="item in sexList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>

          <el-input v-model="item.minAge"
                    clearable
                    placeholder="最小年龄"
                    style="width: 100px;"/>
          <el-input v-model="item.maxAge"
                    clearable
                    placeholder="最大年龄"
                    style="width: 100px;"/>

          <el-input v-model="item.firstValue"
                    clearable
                    placeholder="左边值"
                    style="width: 100px;"/>
          <el-select v-model="item.firstCondition"
                     clearable
                     style="width: 120px"
                     placeholder="关系">
            <el-option v-for="item in fuhaoLeft"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>

          <el-input style="width: 220px"
                    placeholder="请选择"
                    :value="delUndefine(item.indexItemName+item.indexUnit)"
                    @click.native="handleChangeInputToSelect(index)"
                    v-if="item.isShowInput"/>
          <el-select v-else
                     v-model="item.selectItem"
                     value-key="indexItemId"
                     filterable
                     remote
                     reserve-keyword
                     :remote-method="searchMethodIndexItem"
                     :loading="loadingSearch"
                     @change="handleIndexItem"
                     @click.native="handleClickIndex(index)"
                     clearable
                     style="width: 220px"
                     placeholder="请选择">
            <el-option v-for="item in searchIndexList"
                       :key="item.indexItemId"
                       :label="delUndefine(item.name+item.unit)"
                       :value="item">
            </el-option>
          </el-select>

          <el-select v-model="item.secondCondition"
                     clearable
                     style="width: 120px"
                     :disabled="item.firstCondition==1"
                     placeholder="关系">
            <el-option v-for="item in fuhaoRight"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
          <el-input v-model="item.secondValue"
                    clearable
                    placeholder="右边值"
                    :disabled="item.firstCondition==1"
                    style="width: 100px;"/>
          <el-button type="danger" @click="handleDel1(index,item)">删 除</el-button>
        </el-form-item>


        <el-form-item>
          <span style="font-weight: bold;margin-right: 20px">⊙合并病种</span>
          <el-button type="primary" @click="handleAdd2()">增 加</el-button>
        </el-form-item>
        <el-form-item v-for="(item,index) in list2" :key="index+'a'">
          <p>条件{{ item.localId }}:</p>
          <el-select v-model="item.diseaseName"
                     clearable
                     style="width: 260px"
                     filterable
                     placeholder="选择病种">
            <el-option v-for="item in bingzhongExcludList"
                       :key="item.name"
                       :label="item.name"
                       :value="item.name">
            </el-option>
          </el-select>

          <el-select v-model="item.relationType"
                     clearable
                     style="width: 120px"
                     filterable
                     placeholder="选择关系">
            <el-option v-for="item in relationList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>

          <el-button type="danger" @click="handleDel2(index,item)">删 除</el-button>
        </el-form-item>


        <el-form-item>
          <span style="font-weight: bold;margin-right: 20px">⊙合并生活习惯</span>
          <el-button type="primary" @click="handleAdd3()">增 加</el-button>
        </el-form-item>
        <el-form-item v-for="(item,index) in list3" :key="index+'a'">
          <p>条件{{ item.localId }}:</p>
          <el-select v-model="item.lifeStyleId"
                     clearable
                     style="width: 260px"
                     filterable
                     placeholder="生活习惯">
            <el-option v-for="item in xiguanList"
                       :key="item.id"
                       :label="item.content"
                       :value="item.id">
            </el-option>
          </el-select>

          <el-button type="danger" @click="handleDel3(index,item)">删 除</el-button>
        </el-form-item>


        <el-form-item label="条件判断：">
          <el-button type="primary" @click="handleStatus">增 加</el-button>
        </el-form-item>
        <el-form-item v-for="(item,index) in submitData.judges" :key="index+'b'">
          <el-select v-model="item.conditionLocalIds"
                     clearable
                     multiple
                     @click.native="handleChoose()"
                     style="width: 360px"
                     placeholder="请选择条件">
            <el-option v-for="item in submitData.conditions"
                       :key="item.localId"
                       :label="'条件'+item.localId"
                       :value="item.localId">
            </el-option>
          </el-select>
          <el-select v-model="item.conditionType"
                     clearable
                     style="width: 160px"
                     placeholder="请选择满足条件">
            <el-option v-for="item in satisfyList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
          <el-button type="danger" @click="handleDelStatus(index)">删 除</el-button>
        </el-form-item>
      </el-form>
      <p align="center">
        <el-button @click="showDialog=false"
                   type="info">取 消
        </el-button>
        <el-button type="primary"
                   v-prevent-re-click
                   @click="handleSubmit()">确 认
        </el-button>
      </p>

    </el-dialog>

  </div>
</template>
<script>
import ElementTable from '@/base/ElementTable'

export default {
  name: 'zhibingDialog', // 病种管理
  props: {
    dataObj: {
      type: Object,
      default: {}
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      title: '新 增',
      showDialog: false,
      tiaojianShow: false,
      updateShow: false,
      loading: false,
      id: '',
      list: [],
      pageTotal: 0,
      pageIndex: 1,
      pageSize: 20,
      diseaseId: '',

      list1: [],
      list2: [],
      list3: [],
      defaultData: {
        id: '',
        diseaseId: '',
        conditions: [],
        name: '',
        judges: [],
        type: '',
        level: ''
      },
      submitData: {
        id: '',
        name: '',
        diseaseId: '',
        conditions: [],
        judges: [],
        type: '',
        level: ''
      },
      fuhaoRight: [{
        name: '<',
        id: 4
      }, {
        name: '<=',
        id: 5
      }
      ],
      fuhaoLeft: [
        {
          name: '=',
          id: 1
        }, {
          name: '<',
          id: 4
        }, {
          name: '<=',
          id: 5
        }],

      bingzhongExcludList: [],
      zhibiaoList: [],
      liangbiaoList: [],
      xiguanList: [],
      sexList: [{
        name: '男女一致',
        id: 1
      }, {
        name: '男',
        id: 2
      }, {
        name: '女',
        id: 3
      }],
      satisfyList: [{
        name: '全部满足',
        id: 1
      }, {
        name: '任何一满足',
        id: 2
      }, {
        name: '满足任何两个',
        id: 3
      }],
      relationList: [{name: '关联病种', id: 1}, {name: '不关联病种', id: 0}],
      columns: [
        {
          label: '子病名称',
          prop: 'name',
          align: 'center'
        }, {
          label: '创建时间',
          prop: 'addTime',
          align: 'center',
          width: 200,
          formatter: (row, cellValue) => {
            return this.commonFunction.timestampFormat(new Date(row.addTime), 'yyyy-MM-dd hh:mm:ss')
          }
        }, {
          label: '操作',
          prop: 'option',
          align: 'center',
          isSlot: true,
          width: 450
        }
      ],
      searchIndexList: [],
      loadingSearch: false,
      num: 0,
      formModelRules: {
        name: [
          {required: true, message: '请输入子病名称', trigger: 'blur'},
        ],
        type: [
          {required: true, message: '请输入子病分类', trigger: 'blur'},
        ],
        level: [
          {required: true, message: '请输入子病等级', trigger: 'blur'},
        ],
      },
    }
  },
  methods: {
    modalClose() {
      this.$emit('update:visible', false); // 直接修改父组件的属性
    },
    handleAdd() {
      this.showDialog = true
      this.title = '新 增'
      this.list1 = []
      this.list2 = []
      this.list3 = []
      this.num = 0
      this.submitData = {
        id: '',
        diseaseId: '',
        conditions: [],
        name: '',
        judges: [],
        type: '',
        level: ''
      }
      this.getHealthMapDiseaseExcludeList()
    },
    //增加条件
    handleAdd1() {
      var conditions = this.list1.concat(this.list2).concat(this.list3);
      var list1 = this.list1
      if (conditions.length > 0) {
        this.num = Math.max.apply(null, conditions.map(item => item.localId)) + 1
      } else {
        this.num = this.num + 1
      }
      var data = {
        secondCondition: '',
        secondValue: '',
        lifeStyleId: '',
        diseaseId: '',
        localId: this.num,
        indexItemId: '',
        genderCondition: '',
        conditionType: 1,
        firstCondition: '',
        firstValue: '',
        showInput: true
      }
      list1.push(data)
    },
    handleAdd2() {
      var conditions = this.list1.concat(this.list2).concat(this.list3);
      var list2 = this.list2
      if (conditions.length > 0) {
        this.num = Math.max.apply(null, conditions.map(item => item.localId)) + 1
      } else {
        this.num = this.num + 1
      }
      var data = {
        secondCondition: '',
        secondValue: '',
        lifeStyleId: '',
        diseaseId: '',
        localId: this.num,
        indexItemId: '',
        genderCondition: '',
        conditionType: 2,
        firstCondition: '',
        firstValue: '',
      }
      list2.push(data)
    },
    handleAdd3() {
      var conditions = this.list1.concat(this.list2).concat(this.list3);
      var list3 = this.list3
      if (conditions.length > 0) {
        this.num = Math.max.apply(null, conditions.map(item => item.localId)) + 1
      } else {
        this.num = this.num + 1
      }
      var data = {
        secondCondition: '',
        secondValue: '',
        lifeStyleId: '',
        diseaseId: '',
        localId: this.num,
        indexItemId: '',
        genderCondition: '',
        conditionType: 3,
        firstCondition: '',
        firstValue: '',
      }
      list3.push(data)
    },
    handleStatus() {
      var list4 = this.submitData.judges
      var data = {
        conditionLocalIds: [],
        conditionType: ''
      }
      list4.push(data)


    },
    handleDelStatus(index) {
      this.submitData.judges.splice(index, 1)
    }
    ,
    //删除条件
    handleDel1(index, item) {
      this.list1.splice(index, 1)
      this.submitData.conditions = this.list1.concat(this.list2).concat(this.list3)
      this.submitData.judges.forEach(its => {
        its.conditionLocalIds.forEach(itemid => {
          if (item.localId == itemid) {
            its.conditionLocalIds = its.conditionLocalIds.filter(f => f != itemid)
          }
        })
      })

    },
    handleDel2(index, item) {
      this.list2.splice(index, 1)
      this.submitData.conditions = this.list1.concat(this.list2).concat(this.list3)
      this.submitData.judges.forEach(its => {
        its.conditionLocalIds.forEach(itemid => {
          if (item.localId == itemid) {
            its.conditionLocalIds = its.conditionLocalIds.filter(f => f != itemid)
          }
        })
      })
    },
    handleDel3(index, item) {
      this.list3.splice(index, 1)
      this.submitData.conditions = this.list1.concat(this.list2).concat(this.list3)
      this.submitData.judges.forEach(its => {
        its.conditionLocalIds.forEach(itemid => {
          if (item.localId == itemid) {
            its.conditionLocalIds = its.conditionLocalIds.filter(f => f != itemid)
          }
        })
      })
    },
    //点击条件选项合并数组
    handleChoose() {
      this.submitData.conditions = this.list1.concat(this.list2).concat(this.list3)
    },
    //提交数据
    handleSubmit() {
      this.$refs.formModelRef.validate(async (valid) => {
        if (valid) {
          let conditions = this.submitData.conditions;
          let bingzhongExcludList = this.bingzhongExcludList;
          for (let x in bingzhongExcludList) {
            for (let y in conditions) {
              if (bingzhongExcludList[x].name == conditions[y].diseaseName) {
                conditions[y].diseaseType = bingzhongExcludList[x].diseaseType
                conditions[y].diseaseId = bingzhongExcludList[x].diseaseId
              }
            }
          }
          this.updateHealthMapsubDisease()
        }
      })

    },
    //删除条件满足项
    handleDelTiaojianStatus(index) {
      this.judgesData.judges.splice(index, 1)
    },
    //获取子病列表
    getHealthMapsubDiseaseList() {
      this.post(this.api.healthMap.getHealthMapsubDiseaseList, {
        diseaseId: this.diseaseId
      }).then((res) => {
        if (res.data.code === '200') {

          this.list = res.data.object
          this.pageTotal = res.data.totalNum

        }
      })
    },

    //查询指标
    getHealthMapIndexItemList() {
      this.post(this.api.healthMap.getHealthMapIndexItemList).then((res) => {
        if (res.data.code === '200') {
          this.zhibiaoList = res.data.object
        }
      })
    },
    //查询指定病种
    getHealthMapDiseaseExcludeList() {
      this.post(this.api.healthMap.getHealthMapDiseaseAndSubExcludeList, {
        excludeDiseaseId: this.diseaseId,
        excludeSubDiseaseId: this.submitData.id
      }).then((res) => {
        if (res.data.code === '200') {
          this.bingzhongExcludList = res.data.object
        }
      })
    },
    //查询生活习惯
    getHealthMapLifeStyleList() {
      this.post(this.api.healthMap.getHealthMapLifeStyleList).then((res) => {
        if (res.data.code === '200') {
          this.xiguanList = res.data.object
        }
      })
    },
    //更新子病
    updateHealthMapsubDisease() {
      this.submitData.diseaseId = this.dataObj.id
      this.loading = true
      this.post(this.api.healthMap.updateHealthMapsubDisease, this.submitData).then((res) => {
        this.loading = false
        if (res.data.code === '200') {
          this.showDialog = false
          this.getHealthMapsubDiseaseList()
          this.$message.success('更新成功')
        }
      })
    },
    //子病详情
    getHealthMapsubDiseaseDetail() {
      this.post(this.api.healthMap.getHealthMapsubDiseaseDetail, {
        id: this.submitData.id
      }).then((res) => {
        if (res.data.code === '200') {
          var obj = Object.assign(this.submitData, res.data.object);
          this.submitData.name = obj.name
          this.submitData.judges = obj.judges
          this.submitData.conditions = obj.conditions
          this.submitData.type = obj.type
          this.submitData.level = obj.level
          this.submitData.conditions.forEach(item => {
            this.$set(item, 'name', item.diseaseName)
          })
          if (obj.conditions.length > 0) {
            this.num = Math.max.apply(null, obj.conditions.map(item => item.localId))
          } else {
            this.num = obj.conditions.length
          }
          this.list1 = this.submitData.conditions.filter(item => item.conditionType == 1)
          this.list2 = this.submitData.conditions.filter(item => item.conditionType == 2)
          this.list3 = this.submitData.conditions.filter(item => item.conditionType == 3)
          this.list1.forEach(item => {
            this.$set(item, 'isShowInput', true)
          })

        }
      })
    },
    //删除子病
    delHealthMapsubDisease(id) {
      this.post(this.api.healthMap.delHealthMapsubDisease, {
        id: id
      }).then((res) => {
        if (res.data.code === '200') {
          this.showDialog = false
          this.getHealthMapsubDiseaseList()
          this.$message.success('更新成功')
        }
      })
    },
    async handleOption(op, row) {
      switch (op) {

        case 'edit':
          this.submitData = {
            id: '',
            diseaseId: '',
            conditions: [],
            name: '',
            judges: [],
            type: '',
            level: ''
          }
          this.list1 = []
          this.list2 = []
          this.list3 = []
          this.submitData.id = row.id
          this.title = '编 辑'
          this.showDialog = true
          this.getHealthMapsubDiseaseDetail()
          this.getHealthMapDiseaseExcludeList()
          break;
        case 'del':
          this.$confirm('确认删除？', '提示', {
            type: 'warning'
          }).then(() => {
            this.delHealthMapsubDisease(row.id)
          })
          break;
      }
    },

    //搜索指标项
    searchMethodIndexItem(query) {
      if (query !== '') {
        let _this = this;
        _this.loadingSearch = true; // 锁住
        this.post(this.api.healthMap.getSubDiseaseIndexes, {
          searchCondition: query,
          pageIndex: 0,
          pageSize: 10
        }).then(res => {
          if (res.data.code === '200') {
            _this.loadingSearch = false;
            _this.searchIndexList = res.data.object;
          }
        })

      } else {
        this.searchIndexList = [];
      }
    },
    handleClickIndex(index) {
      this.idx = index
    },
    //选中指标项
    handleIndexItem(item) {
      this.$set(this.list1[this.idx], 'indexItemId', item.indexItemId)
      this.$set(this.list1[this.idx], 'indexType', item.indexType)
    },
    handleChangeInputToSelect(index) {

      this.list1[index].isShowInput = false
    },
    // 时间转换
    formatterDate(time) {
      return this.commonFunction.timestampFormat(new Date(time), 'yyyy-MM-dd hh:mm')
    },
    // 时间转换
    delUndefine(str) {
      return this.commonFunction.delUndefine(str)
    },

    // 分页
    handleChangePage(page) {
      this.pageIndex = page;
      this.getHealthMapsubDiseaseList();
    },

  },
  created() {
    this.submitData.diseaseId = this.dataObj.id
    this.diseaseId = this.dataObj.id
    this.getHealthMapsubDiseaseList()
    this.getHealthMapIndexItemList()
    this.getHealthMapLifeStyleList()

  },
  components: {
    'element-table': ElementTable
  }


}
</script>
<style scoped lang="scss">
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.tv1 {
  font-size: 16px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.w-100 {
  width: 100px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
